package com.zx.idc.backend.gui.api.management.codetablepublish.codelist.service.impl;

import com.alibaba.fastjson.JSON;
import com.zx.idc.backend.gui.api.commom.entity.CommandModel;
import com.zx.idc.backend.gui.api.commom.entity.factory.CommandAckFactory;
import com.zx.idc.backend.gui.api.commom.template.IdcCommandTransferTemplate;
import com.zx.idc.backend.gui.api.commom.utils.ExternalHelper;
import com.zx.idc.backend.gui.api.management.codetablepublish.codelist.service.CodeListService;
import com.zx.idc.common.attributes.SchemaFileNameEnum;
import com.zx.idc.common.attributes.SystemAttributes;
import com.zx.idc.common.constants.IdcCommandAckTypeConstants;
import com.zx.idc.ds.common.constant.ReportStatusConstant;
import com.zx.idc.ds.ins.entity.InsAdminControl;
import com.zx.idc.ds.ins.service.IInsAdminControlService;
import com.zx.idc.ds.sys.entity.SysBaseCode;
import com.zx.idc.ds.sys.service.ISysBaseCodeService;
import com.zx.idc.xml.entity.codelist.CodeList;
import com.zx.idc.xml.entity.idccommandack.IdcCommandAck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by hasee on 2019/2/15.
 * 代码表发布指令
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CodeListServiceImpl implements CodeListService {

    private static final Logger LOG = LoggerFactory.getLogger(CodeListServiceImpl.class);

    @Autowired
    private IInsAdminControlService iInsAdminControlService;

    @Autowired
    private IdcCommandTransferTemplate idcCommandTransferTemplate;

    @Autowired
    private ISysBaseCodeService sysBaseCodeService;

    @Override
    public void codeList(CodeList codeList, CommandModel commandModel) {
        LOG.info("代码表发布指令执行开始,指令ID为：{}", codeList.getCommandId());
        try {
            //记录管控指令
            InsAdminControl insAdminControl = new InsAdminControl()
                .setInsType(SystemAttributes.INS_TYPE_CODELIST_PUBLISH)
                .setIdcId(commandModel.getIdcId())
                .setCreateTime(codeList.getTimeStamp())
                .setCommandId(String.valueOf(codeList.getCommandId()))
                .setReportStatus(ReportStatusConstant.NOT_REPORTED)
                .setInsContents(JSON.toJSONString(codeList));
            iInsAdminControlService.insert(insAdminControl);
            sysBaseCodeService.deleteByCodeListType();
            codeList.getJrfs().getJrfsXx().forEach(en -> {
                insertBaseCode(en.getId(), SysBaseCode.TYPE_JRFS, en.getMc(), en.getBz(), en.getSfyx());
            });
            codeList.getDwsx().getDwsxXx().forEach(en -> {
                insertBaseCode(en.getId(), SysBaseCode.TYPE_DWSX, en.getMc(), en.getBz(), en.getSfyx());
            });
            codeList.getZjlx().getZjlxXx().forEach(en -> {
                insertBaseCode(en.getId(), SysBaseCode.TYPE_ZJLX, en.getMc(), en.getBz(), en.getSfyx());
            });
            codeList.getJfxz().getJfxzXx().forEach(en -> {
                insertBaseCode(en.getId(), SysBaseCode.TYPE_JFXZ, en.getMc(), en.getBz(), en.getSfyx());
            });
            codeList.getDllx().getDllxXx().forEach(en -> {
                insertBaseCode(en.getId(), SysBaseCode.TYPE_DLLX, en.getMc(), en.getBz(), en.getSfyx());
            });
            codeList.getFwnr().getFwnrXx().forEach(en -> {
                insertBaseCodeByService(en.getId(), en.getMc(), en.getBz(), en.getFl(), en.getSfyx());
            });
            codeList.getGzlx().getGzlxXx().forEach(en -> {
                insertBaseCode(en.getId(), SysBaseCode.TYPE_GZLX, en.getMc(), en.getBz(), en.getSfyx());
            });
            codeList.getWfwgqk().getWfwgqkXx().forEach(en -> {
                insertBaseCode(en.getId(), SysBaseCode.TYPE_WFWGQK, en.getMc(), en.getBz(), en.getSfyx());
            });
            IdcCommandAck idcCommandAck = CommandAckFactory.ackSuccess(
                IdcCommandAckTypeConstants.CODE_RELEASE_INSTRUCTION,
                commandModel,
                commandAck ->
                    commandAck.setCommandId(codeList.getCommandId())
            );

            ExternalHelper.getExternalWebServiceEnable(() ->
                idcCommandTransferTemplate.transferTemplate(commandModel, idcCommandAck, SchemaFileNameEnum.INFO_SECURITY_MANAGEMENT)
            );
            LOG.info("代码表发布指令执行成功");
        } catch (Exception e) {
            LOG.error("代码表发布指令执行失败,指令ID为：{}", codeList.getCommandId(), e);
            IdcCommandAck idcCommandAck = CommandAckFactory.ackFail(
                IdcCommandAckTypeConstants.CODE_RELEASE_INSTRUCTION,
                commandModel,
                "网络错误，请稍后再试!",
                commandAck ->
                    commandAck.setCommandId(codeList.getCommandId())
            );
            ExternalHelper.getExternalWebServiceEnable(() ->
                idcCommandTransferTemplate.transferTemplate(commandModel, idcCommandAck, SchemaFileNameEnum.INFO_SECURITY_MANAGEMENT)
            );
            throw new RuntimeException(e);
        }

    }

    private void insertBaseCode(Integer code, String type, String mc, String bz, Integer sfyx) {
        sysBaseCodeService.insert(new SysBaseCode()
            .setCode(code)
            .setType(type)
            .setName(mc)
            .setStatus(sfyx == 1 ? SysBaseCode.STATUS_ENABLE : SysBaseCode.STATUS_DISABLE)
            .setOrder(1)
            .setComments(bz));
    }

    private void insertBaseCodeByService(Integer code, String mc, String bz, Integer fl, Integer sfyx) {
        sysBaseCodeService.insert(new SysBaseCode()
            .setCode(code)
            .setType(SysBaseCode.TYPE_FWNR)
            .setName(mc)
            .setStatus(sfyx == 1 ? SysBaseCode.STATUS_ENABLE : SysBaseCode.STATUS_DISABLE)
            .setOrder(1)
            .setComments(bz)
            .setParent(fl));
    }
}
